import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import os
import sys
import time



class Smtp:
    # 邮件发送账号
    from_address = '340665744@qq.com'
    # 接收邮件账号
    to_address = ['13722124885@163.com']
    # 授权码（这个要填自己邮箱开启smtp服务后的授权码）
    from_valid_code = 'ttuhddqvzlmpcaej'
    # 固定写死，测试时使用qq的邮件服务器
    smtp_server_addr = 'smtp.qq.com'
    # 固定端口
    smtp_server_port = 465
    # 编码格式
    charset = 'utf-8'
    text_plain = 'plain'
    text_html = 'html'

    # smtp服务
    smtp_server = ''

    # 初始化邮件服务器、发送者，接受者等信息
    def __init__(self, from_address='340665744@qq.com',
                 to_address=['13722124885@163.com'],
                 from_valid_code='ttuhddqvzlmpcaej',
                 smtp_server_addr='smtp.qq.com',
                 smtp_server_port=465):
        self.from_address = from_address
        self.to_address = to_address
        self.from_valid_code = from_valid_code
        self.smtp_server_addr = smtp_server_addr
        self.smtp_server_port = smtp_server_port
        self.__login()

    def __login(self):
        self.smtp_server = smtplib.SMTP_SSL(self.smtp_server_addr, self.smtp_server_port)
        self.smtp_server.login(self.from_address, self.from_valid_code)

    # 发送消息
    def send(self, message):
        try:

            self.smtp_server.sendmail(self.from_address, self.to_address, message.as_string())
            self.smtp_server.quit()
            print('邮件发送成功！')
        except Exception as e:
            print('邮件发送失败！' + e)


    '''
        制作文本邮件
        参数说明：
            主题
            编码
            发件人标题
            收件人标题
            文本格式
            文本内容
    '''
    def getTextMessage(self, subject, charset, from_header, to_header, text_style,  text_content):
        if (charset != None):
            self.charset = charset

        # 发送的邮件信息
        message = MIMEText(text_content, text_style, charset)
        # 发件人
        message['From'] = Header(from_header, charset)
        # 收件人
        message['To'] = Header(to_header, charset)
        # 邮件标题
        message['Subject'] = Header(subject, charset)

        return message


    '''
        获取带附件的邮件信息
    '''
    def getMultipartMessage(self, subject, charset, from_header, to_header, text_style,  text_content, files):
        if (charset != None):
            self.charset = charset
        # 创建一个带附件的实例
        message = MIMEMultipart('alternative')
        # 发件人
        message['From'] = Header(from_header, charset)
        # 收件人
        message['To'] = Header(to_header, charset)
        # 邮件标题
        message['Subject'] = Header(subject, charset)

        # 邮件正文内容
        message.attach(MIMEText(text_content, text_style, charset))

        for file in files.values():
            # 文件路径
            filePath = file[0] + file[1]
            # 判断是否是文件
            if os.path.isfile(filePath):
                appendix = MIMEText(open(filePath, 'rb').read(), 'base64', "utf-8")
                # att = MIMEText(open(path + '/' + file, 'rb').read(), 'base64', 'utf-8')

                appendix["Content-type"] = "application/octet-stream"
                appendix.add_header("Content-Disposition", "attachment", filename=('utf-8', '', file[1]))
                message.attach(appendix)
            pass

        return message


subject = "七舰队网吧（主题）"
charset = "utf-8"
from_header = "七舰队网吧（管理员）"
to_header = "焦雪飞（会员）"
text_style = "plain"
text_content = '''
    尊敬的用户您好：
        由于您长时间未到本店消费，现已取消您的会员。
                                                                                    --七舰队网吧（呼和浩特）
                                                                                    电话：18511745544
'''
file0 = ['./', 'test1.txt']
file1 = ['./', 'test2.txt']
file2 = ['../', 'json.py']
files = {}
files[0] = file0
files[1] = file1
files[2] = file2


smtp = Smtp()
# 发送普通文本邮件信息
# message = smtp.getTextMessage(subject, charset, from_header, to_header, text_style, text_content)
# 发送带有附件的邮件信息
message = smtp.getMultipartMessage(subject, charset, from_header, to_header, text_style, text_content, files)
# print(message)
smtp.send(message)


